package com.fashionbrot.github.util;

import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

@Slf4j
public class ScriptUtil {

    public static  double eval(String script,double z1,double t,double totalCapacity){
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine scriptEngine = sem.getEngineByName("js");


        try {
            scriptEngine.eval(script);
            Object z2 = ((Invocable) scriptEngine).invokeFunction("rqdljh", z1, t, totalCapacity);
            if (z2!=null){
                return  StringUtil.parseDouble(z2.toString());
            }
        } catch (Exception e) {
            log.error("script:{}  z1:{} t:{} totalCapacity:{}",script,z1,t,totalCapacity);
            log.error("eval error",e);
        }
        return 0D;
    }


    public static void main(String[] args) {
        String script = "function rqdljh(z1,t,totalCapacity){var z2 =0;if (t <= -80) { z2 = 0;}else if(-80<t && t<-5){z2 = 1-((-5-t)/75*0.9);}else if(-5<=t && t<=5){z2 = 1;}else if(5<t && t<80){z2 = 1+((t-5)/75*0.8);}else if(t>=80){z2 = 2; }var rqdljh = z1 * z2;if (rqdljh>totalCapacity){rqdljh = totalCapacity ;}return rqdljh;}";
        System.out.println(eval(script,14.524,-239.7788879711999,48));
    }

}
